<script setup lang="ts">
import { onMounted, ref } from "vue";
import OSS from "ali-oss";

import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { v4 as uuidv4 } from 'uuid';
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue';
import type { UploadProps, UploadUserFile } from 'element-plus'
const fileList = ref([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false);

// 文件列表改变事件
const onFileChange = (file: UploadFile) => {
  fileList.value.push(file);
  //('File changed:', fileList.value);
};

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  //console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
  //console.log(uploadFile.url)
}




import {
  select,
  addTaskManger,
  addTaskSave,
  selectTaskSave,
  addImage,
  selectTaskManagerByTaskId,
  updateCommit,
} from "@/api/common/work/SelectWork.js";

import { useRoute } from "vue-router";



import router from "@/router";
import { list } from "ali-oss/lib/object";
const route = useRoute();


const isCollapse = ref(true);

// //学校信息数据模型
// const schoolInfo = {
//   name: "北京邮电大学",
//   address: "北京市海淀区",
//   tel: "010-12345678",
//   email: "post@bjtu.edu.cn",
//   logo: "",
// };
//用户信息数据模型
const userInfo = {
  name: "XXX",
  image: "",
};

//作业对象
const task = ref({});
//测试数据


// onMounted(() => {
//   taskId.var name = value = route.query.taskId;
//   console.log(taskId.value);

// });

//获取作业信息
const selectTask = async () => {
  let res = await select(route.query.taskId);
  task.value = res.data;
};
selectTask();
//获取已保存的作业信息
const selectTaskRedis = async () => {
  let res = await selectTaskSave(route.query.taskId);
  taskSave.value = res.data;
  if (taskSave.value.taskInfo != null) {
    document.getElementById("editableDiv").innerHTML = taskSave.value.taskInfo;
  }
};
selectTaskRedis();
//当前保存的图片路径
const taskImg = ref();
//当前保存的附件路径
const path = ref();
//将当前保存的作业信息存入redis中
// const addTaskSaveRedis = async () => {
//   taskSave.value.taskId = task.value.taskId;
//   //上传图片
//   if (taskImg.value != null) {
//     let result1 = await addImage(taskImg.value);
//     taskSave.value.taskImg = result1.data;
//   }
//   //上传附件
//   if (path.value != null) {
//     let result2 = await addImage(path.value);
//     taskSave.value.taskPath = result2.data;
//   }

//   //保存到redis
//   await addTaskSave(taskSave.value);

//   location.reload()
// };

//查询当前学生是否已提交作业
const selectTaskManager = async () => {
  let res = await selectTaskManagerByTaskId(route.query.taskId);
  if (res.data == 0) {
    isSubmit.value = true;
  }
  if (res.data.commit == 1) {
    taskManger.value = res.data;
    isSubmit.value = true;
  }
  if (res.data.commit == 0) {
    isSubmit.value = false;
    taskManger.value = res.data;
  }
};
selectTaskManager();

//定义当前保存的对象
const taskSave = ref({});

//将当前完善的作业信息保存到taskManger中
const saveTaskManger = async () => {
  //上传图片
  if (fileList.value.length > 0) {
    let result1 = await addImage(fileList.value);
    taskSave.value.taskImg = result1.data;
  }


  //上传附件
  // if (path.value != null) {
  //   let result2 = await addImage(path.value);
  //   taskSave.value.taskPath = result2.data;
  // }
  //作业id
  taskManger.value.taskId = task.value.taskId;
  //教师id
  taskManger.value.teacherId = task.value.teacherId;
  //作业内容
  taskManger.value.taskTxt = taskSave.value.taskInfo;
  //作业图片路径
  taskManger.value.imageUrl = taskSave.value.taskImg;
  //console.log(taskManger.value);
  let res = await addTaskManger(taskManger.value);
  if (res.code == 200) {
    ElMessage({
      message: "提交成功",
      type: "success",
    });
  } else {
    ElMessage({
      message: "提交失败",
      type: "error",
    });
  }
  //location.reload()
};
//判断作业内容是否为空
const isTaskInfoEmpty = () => {
  return taskSave.value == null;
};

//插入图片并回显在div上
// const insertImage = (imageSrc) => {
//   const editableDiv = document.getElementById("editableDiv");
//   const img = document.createElement("img");
//   img.src = imageSrc;
//   img.style.width = "200px";
//   img.style.height = "200px";
//   img.style.border = "1px solid black";
//   editableDiv.appendChild(img);
// };

//插入zip文件
const insertZipFile = (zipFilePath) => {
  const editableDiv = document.getElementById("editableDiv");
  const link = document.createElement("a");
  link.href = zipFilePath;
  link.textContent = "下载 ZIP 文件"; // 添加文本内容
  link.download = true; // 设置 download 属性
  link.target = "_blank"; // 可选: 在新标签页打开
  // 添加一个点击事件处理器来触发下载
  link.addEventListener("click", function (event) {
    event.preventDefault(); // 阻止默认行为
    // 这里可以添加额外的逻辑，比如检查文件是否存在等
    // 下面的代码会模拟点击行为来触发下载
    link.click();
  });
  editableDiv.appendChild(link);
};

//选择图片
function showFileChooser() {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = "image/*";
  input.click();
  input.addEventListener("change", function () {
    const file = this.files[0];
    const formData = new FormData();
    formData.append("file", file);
    //console.log(formData);
    var reader = new FileReader();
    // 当文件读取完成后调用此函数
    reader.onload = function (e) {
     // console.log(file);
      insertImage(e.target.result);
    };
    taskImg.value = formData;
    // 读取文件内容
    reader.readAsDataURL(file);
  });
}
//选择文件
function showFileChooser1() {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = "application/zip";
  input.click();
  input.addEventListener("change", function () {
    const file = this.files[0];
    const formData = new FormData();
    formData.append("file", file);
    var reader = new FileReader();
    // 当文件读取完成后调用此函数
    reader.onload = function (e) {
     // console.log(file);
      insertZipFile(e.target.result);
    };
    path.value = formData;
    // 读取文件内容
    reader.readAsDataURL(file);
  });
}

//判断当前是否已提交作业
const isSubmit = ref(false)

//页面加载完成后执行
// document.addEventListener("DOMContentLoaded", async function () {
//   await selectTaskRedis();
//   await selectTaskManager();
//   const editableDiv = document.getElementById("editableDiv");
//   const placeholder = editableDiv.getAttribute("data-placeholder");
//   let initialValue = taskManger.value.taskTxt || taskSave.value.taskInfo || placeholder;
//   editableDiv.innerHTML = initialValue;
//   editableDiv.addEventListener("focus", function (e) {
//     const value = e.target.innerHTML;
//     if (value === placeholder) {
//       e.target.innerHTML = "";
//     }
//   });

//   editableDiv.addEventListener("blur", function (e) {
//     const value = e.target.innerHTML;
//     if (value.trim() === "") { // 使用trim()去除空白字符
//       e.target.innerHTML = placeholder;
//     }
//   });
//   if (taskSave.value.taskImg != null) {
//     // 假设这是你的图片URL
//     const imageUrl = taskSave.value.taskImg;
//     const img = document.createElement("img");
//     // 创建一个img元素并设置其src属性
//     img.src = imageUrl;
//     img.style.width = "200px";
//     img.style.height = "200px";
//     img.style.border = "1px solid black";
//     // 将img元素添加到#imageContainer中
//     document.getElementById("editableDiv").appendChild(img);
//   }

//   if (taskManger.value.imageUrl != null) {
//     // 假设这是你的图片URL
//     const imageUrl = taskManger.value.imageUrl;
//     const img = document.createElement("img");
//     // 创建一个img元素并设置其src属性
//     img.src = imageUrl;
//     img.style.width = "200px";
//     img.style.height = "200px";
//     img.style.border = "1px solid black";
//     // 将img元素添加到#imageContainer中
//     document.getElementById("editableDiv").appendChild(img);
//   }

// if (taskSave.value.taskPath != null) {
//   // 假设这是ZIP压缩包的下载链接
//   const zipUrl = taskSave.value.taskPath;
//   // 创建一个a元素来作为ZIP压缩包的下载链接
//   const zipLink = document.createElement("a");
//   zipLink.href = zipUrl;
//   zipLink.textContent = "下载ZIP压缩包";
//   zipLink.target = "_blank"; // 可选，在新标签页中打开链接
//   zipLink.href = "@/assets/img/123.webp"
//   // 将a元素添加到#zipLinkContainer中
//   document.getElementById("editableDiv").appendChild(zipLink);
// }

// if (taskManger.value.attachmentUrl != null) {
//   // 假设这是ZIP压缩包的下载链接
//   const zipUrl = taskManger.value.attachmentUrl;
//   // 创建一个a元素来作为ZIP压缩包的下载链接
//   const zipLink = document.createElement("a");
//   zipLink.href = zipUrl;
//   zipLink.textContent = "下载ZIP压缩包";
//   zipLink.target = "_blank"; // 可选，在新标签页中打开链接
//   // 将a元素添加到#zipLinkContainer中
//   document.getElementById("editableDiv").appendChild(zipLink);
// }


// });

//将写入的内容存入taskSave中
function handleInput(event) {
  taskSave.value.taskInfo = event.target.innerHTML;
  taskManger.value.taskTxt = event.target.innerHTML
}

const over = async () => {
  let res = updateCommit(taskManger.value.id)
  if (res.code == 200) {
    ElMessage({
      message: "请重新编辑",
      type: "success",
    });
  }
  location.reload()
}

const back = () => {
  history.go(-1)
}

const client = new OSS({
  region: 'oss-cn-beijing',
  accessKeyId: 'LTAI5t72SP9uEs3mxZR89cAa',
  accessKeySecret: 'aSAPxfIZwFYzJVlwdD0KUpE9wqABJp',
  bucket: 'saas-os',
  timeout: 600 * 1000
});
const uuid = ref('')
let currentFile = null;
let isUploading = ref(false);
let uploadProgress = ref(0);
const uploadFile = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  currentFile = file;
  isUploading.value = true;
  uploadProgress.value = 0;

  // 对文件名进行URL编码
  uuid.value = uuidv4();
  const encodedFileName = encodeURIComponent(uuid.value + '%' + file.name);
  try {
    // 使用编码后的文件名进行上传
    const result = await client.multipartUpload(encodedFileName, file, {
      progress: (p) => {
        uploadProgress.value = Math.round(p * 100);
      },
    });
    const xb = result.res.requestUrls[0].lastIndexOf("?");
    const uurl = result.res.requestUrls[0].slice(0, xb)
    taskManger.value.attachmentUrl = uurl
   // console.log(taskManger.value)
    isUploading.value = false;
  } catch (err) {
    isUploading.value = false;
  }
};

//定义作业管理信息对象
const taskManger = ref({});


</script>

<template>

  <div class="common-layout">
    <el-container>
      <!-- 头部 -->
      <div class="main">
        <div class="header">
          <div class="back" @click="back()">
            <img src="@/assets/img/返回.svg" alt="" />
          </div>
          <span>作业详情</span>
        </div>
        <div class="topic" v-if="isSubmit">
          <div class="topicname">
            <span>{{ task?.section?.sectionName }}</span>
          </div>
          <div class="topiccontent">
            <p>{{ task.taskName }}</p>
          </div>

        </div>

        <div class="topic" v-else>
          <div class="topicname">
            <span>{{ task?.section?.sectionName }}</span>
          </div>
          <div class="topiccontent">
            <p>{{ task.taskName }}</p>
          </div>
          <div class="topiccontent1">
            <p class="aaa">老师对你的评分为:<span>{{ taskManger.score }}</span>分</p>
            <p class="aaa">老师对你的评语为:<span>{{ taskManger.comment }}</span></p>
          </div>

        </div>


        <div class="bottom" v-if="isSubmit">
          <div class="bottom-content">
            <div class="bottom-top">
              <div class="my-answer">
                <span>我的回答</span>
              </div>
              <div class="my-other">
                <!-- <img src="@/assets/img/fujian.jpg" />
                <span @click="showFileChooser()">上传图片</span> -->
                <!-- <img src="@/assets/img/fujian.jpg" /> -->
                <!-- <span @click="showFileChooser1()">上传附件</span> -->
              </div>
            </div>
            <div class="bottom-bottom">

              <div contenteditable="true" id="editableDiv" data-placeholder="请输入您的答案" @input="handleInput"></div>
              <el-upload v-model:file-list="fileList" list-type="picture-card" :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove" @change="onFileChange" :auto-upload="false" multiple>
                <el-icon>
                  <Plus />
                </el-icon>
              </el-upload>

              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
              </el-dialog>
              <p>请在此上传作业附件</p>
              <label class="upload-btn" for="scspan">上传附件</label>
              <input type="file" @change="uploadFile" id="scspan" />
              <div v-if="isUploading">
                正在上传: {{ currentFile.name }}...
                <progress :value="uploadProgress" max="100"></progress>
              </div>
            </div>

            <div class="bottom-button">
              <button class="button-01" @click="saveTaskManger()" v-if="taskSave != null">
                提交作业
              </button>
              <!-- <button class="button-02" @click="addTaskSaveRedis()" v-if="taskSave != null">
                保存内容
              </button> -->
            </div>
          </div>
        </div>

        <div class="bottom" v-else>
          <div class="bottom-content">
            <div class="bottom-top">
              <div class="my-answer">
                <span>已提交回答</span>
                <span style="margin-left: 10px;">{{ taskManger.submitTime }}</span>
                <span style="margin-left: 10px;"> 提交了第{{ taskManger.submitCount }}次回答</span>
                <span style="margin-left: 730px;border" @click="over()">重新编辑</span>
              </div>
            </div>
            <div class="bottom-bottom">
              <div contenteditable="true" id="editableDiv" @input="handleInput">{{ taskManger.taskTxt }}</div>
            </div>
          </div>
        </div>
        <router-view />
      </div>
    </el-container>
  </div>
</template>

<style scoped lang="scss">
.button-disabled {
  opacity: 0.5;
  pointer-events: none;
  background-color: black; // 可以根据需要修改背景色
  color: white; // 可以修改文字颜色
}

/* 舞台样式 */
.common-layout {
  background-color: white;
}

.main {
  width: 100%;
  height: 973px;
}

.aaa {
  height: 50px;
  font-size: 20px;

  span {
    margin-left: 10px;
    font-weight: bold;
    /* 添加这一行以使文本加粗 */
  }
}

.topic .topiccontent1 {
  width: 95%;
  height: 100px;
  margin: auto;
}

.header {
  width: 100%;
  height: 60px;
  display: flex;
  flex-direction: row;
  /* margin-left: 110px; */
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.header .back {
  width: 60px;
  height: 60px;
  margin-left: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.header .back img {
  width: 55%;
  height: 55%;
}

.header span {
  line-height: 60px;
  font-size: 22px;
}

.topic {
  width: 100%;
  height: 240px;
  display: flex;
  flex-direction: column;
}

.topic .topicname {
  width: 100%;
  height: 80px;
  text-indent: 2em;
}

.topic .topicname span {
  line-height: 50px;
  font-size: 20px;
  font-family: Source Han Sans SC VF;
}

.topic .topiccontent {
  width: 100%;
  height: 100px;
}

.topic .topiccontent p {
  font-size: 16px;
  margin-left: 0px;
  text-indent: 2em;
  font-family: Source Han Sans SC VF;
}

.bottom {
  width: 90%;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  // margin: 0 auto;
}

.bottom-content {
  width: 95%;
  height: 70%;

}

.bottom-top {
  width: 100%;
  height: 80px;
  border: 1px solid rgba(70, 62, 62, 0.3);
  display: flex;

}

.my-answer {
  margin-left: 20px;
  font-size: 17px;
  line-height: 80px;
}

.my-other {
  height: 100%;
  width: 210px;
  margin-left: auto;
  line-height: 80px;
  font-size: 17px;
}

.my-other img {
  width: 16px;
  height: 16px;
}

.my-other span {
  cursor: pointer;
  margin-right: 19px;
}

.bottom-bottom {
  width: 100%;
  min-height: 200px;
  // overflow: hidden;
}

.bottom-bottom #editableDiv {
  width: 100%;
  min-height: 177px;
  text-indent: 2em;
  border: none;
  display: flex;
  // align-items: center;
  padding-top: 20px;
  // resize: none;
  font-size: 16px;
  flex-wrap: wrap;
  flex-flow: column;
  border: 1px solid rgba(0, 0, 0, 0.3);
  color: black;
  // overflow: scroll;
}

.bottom-bottom #editableDiv:focus {
  outline: none;
}

.bottom-button {
  width: 100%;
  height: 35px;
  margin-top: 30px;
}

.bottom-button button {
  width: 87.6px;
  height: 32px;
  float: right;
}

.button-02 {
  margin-right: 20px;
  background-color: white;
  border: 1px solid #fb5234;
  border-radius: 6px;
  color: #fb5234;
}

.button-01 {
  background-color: #fb5234;
  border: none;
  border-radius: 6px;
  color: white;
}
</style>